package com.googlecode.restitory.api.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.googlecode.restitory.api.ConflictException;
import com.googlecode.restitory.api.JsonService;

public class JsonBatchServlet extends HttpServlet {

	private static final long serialVersionUID = -4139667332531565175L;

	private static final Logger LOG = LoggerFactory
			.getLogger(JsonBatchServlet.class);

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			super.service(req, resp);
		} catch (ConflictException e) {
			LOG.warn("Conflict", e);
			resp.sendError(409);
		}
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		JsonService service = getJsonService();

		JsonArray result = new JsonArray();
		String[] values = req.getParameterValues("id");
		if (values != null) {
			for (String id : values) {
				JsonObject jsonObject = service.get(id);
				if (jsonObject != null) {
					result.add(jsonObject);
				}
			}
		}

		ServletHelper.write(resp, result);
	}

	private static JsonService getJsonService() {
		return JsonServiceFilter.get();
	}
}
